import { debounce } from '@/util/common'

// input 字符串长度限制，中文字符算两个
export default {
    mounted(el, binding) {
        el = el.nodeName !== 'INPUT' ? el.querySelector('input') : el
        if (!el) return

        let flag = false
        el.addEventListener('compositionstart', () => {
            flag = true
        })
        el.addEventListener('compositionend', () => {
            flag = false
        })
        el.addEventListener('keyup', debounce(() => {
            if (flag) return

            let str = el.value
            let oldStr = el.value
            const maxlen = binding.value
            let endIndex = getEndIndex(str, maxlen) + 1
            str = str.slice(0, endIndex)
            el.value = str

            // 避免反复触发
            if (oldStr != el.value) {
                el.dispatchEvent(new UIEvent('input'))
            }
        }))
    }
}

// 获取需要截断的末尾索引
function getEndIndex(str, maxlen) {
    let len = 0
    let end = 0
    for (let i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 127) {
            len += 2
        } else {
            len++
        }

        if (len > maxlen) {
            end = i - 1
            break
        }
        end = i
    }
    return end < 0 ? 0 : end
}
